package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.OrderInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.service.BuyerOrderService;
import com.example.demo.util.ConstVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/buyer/order")
public class BuyerOrderController {
    private static final Logger log = LoggerFactory.getLogger(BuyerOrderController.class);

    @Autowired
    private BuyerOrderService buyerOrderService;

    @GetMapping("/list")
    public AjaxResult getBoughtOrders(HttpSession session, String status) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            List<OrderInfo> orders = buyerOrderService.getBoughtOrders(userInfo.getId(), status);
            log.info("Found {} orders for user {}, status: {}", orders.size(), userInfo.getId(), status);
            log.debug("Order details: {}", orders);
            
            return AjaxResult.success(orders);
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return AjaxResult.fail("获取订单列表失败");
        }
    }

    @GetMapping("/listComment")
    public AjaxResult getBoughtOrdersComment(HttpSession session, String status) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            List<OrderInfo> orders = buyerOrderService.getBoughtOrdersComment(userInfo.getId(), status);
            log.info("Found {} orders for user {}, status: {}", orders.size(), userInfo.getId(), status);
            log.debug("Order details: {}", orders);
            
            return AjaxResult.success(orders);
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return AjaxResult.fail("获取订单列表失败");
        }
    }

    @GetMapping("/detail/{orderNo}")
    public AjaxResult getOrderDetail(@PathVariable String orderNo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            OrderInfo order = buyerOrderService.getOrderDetail(orderNo, userInfo.getId());
            if (order == null) {
                return AjaxResult.fail("订单不存在");
            }
            
            return AjaxResult.success(order);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return AjaxResult.fail("获取订单详情失败");
        }
    }

    @PostMapping("/confirm-receive")
    public AjaxResult confirmReceive(@RequestParam String orderNo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            int success = buyerOrderService.confirmReceipt(orderNo, userInfo.getId());
            return success > 0 ? AjaxResult.success("确认收货成功") : AjaxResult.fail("确认收货失败");
        } catch (Exception e) {
            log.error("确认收货失败", e);
            return AjaxResult.fail("确认收货失败");
        }
    }

    @PostMapping("/cancel")
    public AjaxResult cancelOrder(@RequestParam String orderNo, 
                                @RequestParam(required = false) String reason,
                                HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            int success = buyerOrderService.cancelOrder(orderNo, userInfo.getId(), reason);
            return success > 0 ? AjaxResult.success("取消订单成功") : AjaxResult.fail("取消订单失败");
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return AjaxResult.fail("取消订单失败");
        }
    }

    @PostMapping("/delete")
    public AjaxResult deleteOrder(@RequestParam String orderNo, 
                                @RequestParam(required = false) String reason,
                                HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            int success = buyerOrderService.deleteOrder(orderNo, userInfo.getId(), reason);
            return success > 0 ? AjaxResult.success("删除成功") : AjaxResult.fail("删除失败");
        } catch (Exception e) {
            log.error("删除订单失败", e);
            return AjaxResult.fail("删除订单失败");
        }
    }

    @GetMapping("/express/{orderNo}")
    public AjaxResult getExpressInfo(@PathVariable String orderNo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            Map<String, Object> expressInfo = buyerOrderService.getExpressInfo(orderNo, userInfo.getId());
            if (expressInfo == null) {
                return AjaxResult.fail("物流信息不存在");
            }
            
            return AjaxResult.success(expressInfo);
        } catch (Exception e) {
            log.error("获取物流信息失败", e);
            return AjaxResult.fail("获取物流信息失败");
        }
    }

    @GetMapping("/cancel-reason/{orderNo}")
    public AjaxResult getCancelReason(@PathVariable String orderNo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            String reason = buyerOrderService.getCancelReason(orderNo, userInfo.getId());
            return AjaxResult.success(Map.of("reason", reason));
        } catch (Exception e) {
            log.error("获取取消原因失败", e);
            return AjaxResult.fail("获取取消原因失败");
        }
    }

    @PostMapping("/update-address")
    public AjaxResult updateAddress(@RequestBody Map<String, String> params, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            String orderNo = params.get("orderNo");
            String addressId = params.get("addressId");
            
            if (orderNo == null || addressId == null) {
                return AjaxResult.fail("参数不完整");
            }
            
            int success = buyerOrderService.updateAddress(orderNo, userInfo.getId(), Integer.parseInt(addressId));
            
            return success > 0 ? AjaxResult.success("修改地址成功") : AjaxResult.fail("修改地址失败");
        } catch (Exception e) {
            log.error("修改收货地址失败", e);
            return AjaxResult.fail("修改收货地址失败");
        }
    }
} 